import cm_client

from core.logger import logger
from setting import config


class CM6(object):
    def __init__(self, protocol="http", host=config.CM_HOST, port=config.CM_PORT, username=config.CM_USERNAME,
                 password=config.CM_PASSWORD):
        self.protocol = protocol
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.api_client = self._init()
        self.cm_client = self._cm_client_auth()

    def _cm_client_auth(self):
        cm_client.configuration.username = self.username
        cm_client.configuration.password = self.password

        return cm_client

    def _init(self):
        try:
            api_url = f"{self.protocol}://{self.host}:{self.port}/api/v30"
            cm_client.configuration.username = self.username
            cm_client.configuration.password = self.password
            self.api_client = cm_client.ApiClient(api_url)
        except Exception as e:
            logger.error(e)
            return False
        return self.api_client

    def api_v17_init(self):
        api_url = f"{self.protocol}://{self.host}:{self.port}/api/v17"
        return api_url

    def get_clusters(self):
        cluster_api_instance = cm_client.ClustersResourceApi(self.api_client)
        api_response = cluster_api_instance.read_clusters(view='SUMMARY')
        for cluster in api_response.items:
            print(cluster.name, "-", cluster.full_version)

    def check_service(self, cluster_name, service_name='IMPALA'):
        """
        :param cluster_name:
        :param service_name:
        :return:
        """
        services_api_instance = cm_client.ServicesResourceApi(self.api_client)
        services = services_api_instance.read_services(cluster_name, view='FULL')
        for service in services.items:
            # print(service.name, "-", service.type)
            if service.type == service_name:
                return service_name.lower()

            print("Error: Could not locate Impala Service")
            quit(1)

    def get_kudu_table_disk_size(self, from_time, to_time):
        query = "select total_kudu_on_disk_size_across_kudu_replicas where category=KUDU_TABLE "
        result = {}
        api_instance = cm_client.TimeSeriesResourceApi(self.api_client)
        data = api_instance.query_time_series(_from=from_time, query=query, to=to_time)
        if not data:
            logger.error(f"get cm kudu table is null")
            return False
        for item in data.items[0].time_series:
            try:
                result.update(
                    {item.metadata.attributes["kuduTableId"]: item.data[0].value})
            except Exception as e:
                logger.error(f"get kudu table disk_size: {item} error =>{e}")
                return {}

        return result


if __name__ == '__main__':
    cm = CM6(host="192.168.63.181", username="cm_api", password="welabapi@2023")
    cm.get_clusters()
#     print(cm.get_kudu_table_disk_size())
